import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import './utils/rem'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import axios from 'axios';
import './assets/global.css'
import {connectWebSocket, disconnectWebSocket} from './utils/websocket';

Vue.use(ElementUI);
axios.defaults.withCredentials = true;
axios.defaults.baseURL = process.env.VUE_APP_API_BASE_URL;
Vue.prototype.$http = axios;
Vue.config.productionTip = false;
Vue.prototype.$bus = new Vue()
// 1. 保存 Vue 实例
new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app');

// 2. 获取用户信息
const user = JSON.parse(localStorage.getItem('user') || '{}');
const userName = user.username;
console.log('Current userName:', userName);

// 3. 监听 WebSocket 消息
if (userName) {
    connectWebSocket(userName, (msgObj) => {
        console.log('Received message in main.js:', msgObj);
        // 这里要确保 notifyDialog 已经渲染
        Vue.prototype.$bus.$emit('showNotifyDialog', msgObj)
    });
}

window.addEventListener('beforeunload', () => {
    disconnectWebSocket();
});
